layui.use(['form', 'table', 'layer', 'laydate'], function () {
    var $ = layui.jquery,
        form = layui.form,
        layer = layui.layer,
        laydate = layui.laydate,
        table = layui.table;

    table.render({
        elem: '#currentTableId',
        url: '../api/product/findProductPage',
        request: {
            pageName: 'current' //页码的参数名称，默认：page
            , limitName: 'size' //每页数据量的参数名，默认：limit
        },
        cols: [[
            {field: 'pid', width: 180, title: '产品编号', sort: true, align: "center"},
            {field: 'pname', width: 180, title: '产品名称', align: "center", templet: setOperate,},
            {field: 'parea', width: 180, title: '产地', align: "center"},
            {field: 'pml', width: 180, title: '产品规格', align: "center"},
            {title: '修改信息', minWidth: 50, templet: '#currentTableEdit', fixed: "right", align: "center"},
            {title: '更新价格', minWidth: 50, templet: '#currentTableEditPrice', fixed: "right", align: "center"},
            {title: '下架', minWidth: 50, templet: '#currentTableBar', fixed: "right", align: "center"}
        ]],
        limits: [10, 15, 20, 25, 50, 100],
        limit: 10,
        page: true
    });

    function setOperate(data) {
        var pid = data.pid;
        var pname = data.pname;
        var btn = "";
         btn += '' + pname + '';
         return '<a href="product-price.html?pid='+pid+'"><i class="layui-icon layui-icon-search "></i></a>' +btn ;
       // location.href = 'product-price.html?pid=' + data.pid;

    }
    //查询所有下架的类别
    function tableReload() {
        var pis = 0;
        table.reload('currentTableId', {
            url: '../api/product/uppProductxia',
            where: {
                pis: pis
            }
            , page: {
                curr: 1 //重新从第 1 页开始
            }
        });
    }

    $(".data-uppxia-product").click(function () {
        $("#currentTableBar").html(`<a class="layui-btn layui-btn-xs layui-btn-danger  " lay-event="uppshang">恢复商品</a>`)
        tableReload();
    });

    //查询未下架的商品
    function tableReload1() {
        var pis = 1;
        table.reload('currentTableId', {
            url: '../api/product/uppProductxia',
            where: {
                pis: pis
            }
            , page: {
                curr: 1 //重新从第 1 页开始
            }
        });
    }

    $(".data-product").click(function () {
        $("#currentTableBar").html(`<a class="layui-btn layui-btn-xs layui-btn-danger data-count-uppshang" lay-event="delete">下架 </a>`)
        tableReload1();
    });




//点击名字跳转到个人信息页面
    /*        function openClientMes(pid) {
                window.location.href = '../api/sort/uppxia';
            }*/

    // 监听搜索操作
    form.on('submit(data-search-btn)', function (data) {
        var result = JSON.stringify(data.field);
        layer.alert(result, {
            title: '最终的搜索信息'
        });

        //执行搜索重载
        table.reload('currentTableId', {
            page: {
                curr: 1
            }
            , where: {
                searchParams: result
            }
        }, 'data');

        return false;
    });


    // 监听添加操作
    $("#addProduct").on("click", function () {
        layer.open({
            type: 1,//此处以iframe举例
            title: '新增商品'
            , area: ['30%', '70%']
            //, shade: 1
            , btnAlign: 'c' //按钮居中
           , shade: [0.3, '#2F4056']
           // , resize: false
             , maxmin: true
            , content: $("#window").html(), ////'add-product.html'
            // , btn: ['提交', '关闭'],
            success: function (layero, index) {

            },
            yes: function () {
                /* form.render();
                var body = layer.getChildFrame('body', index);
                body.contents().find('#pName').val(data.pname);
                body.contents().find('#pArea').val(data.parea);
                body.contents().find('#pMl').val(data.pml);
                body.contents().find('#sName').val(data.sname);*/

            }

        });
        form.render();//动态渲染


    });
    form.on('submit(productAdd)', function (data) {
        var param = data.field;
        console.log(param)
        console.log(JSON.stringify(param));
        $.ajax({
            url: '/api/product/saveProduct',
            method: 'post',
            //data: {"pName":dt.pname,"pArea":dt.parea, "pMl":dt.pml, "sName":dt.sname},
           data: data.field,
            // data:$("#product").val(),
            dataType: 'json',
            success: function (res) {
                if (res.code = '0') {
                    parent.closeIframe(res.msg);
                } else
                    alert(res.msg);
            },
            error: function (data) {

            }
        });
        layer.closeAll(index);
    });


    $.get({
        url: "../api/product/productList", success: (resp) => {
            resp.forEach(r => {
                console.log(r)
                $("#pMl").append("<option value='" + r.pid + "'>" + r.pml + "</option>");
            });
        }, dataType: "json"
    });

    $.get({
        url: "../api/sort/sortList", success: (resp) => {
            resp.forEach(r => {
                console.log(r)
                $("#sName").append("<option value='" + r.sid + "'>" + r.sname + "</option>");
            });
        }, dataType: "json"
    });


    // 监听删除操作
    $(".data-delete-btn").on("click", function () {
        var checkStatus = table.checkStatus('currentTableId')
            , data = checkStatus.data;
        layer.alert(JSON.stringify(data));
    });

    //监听表格复选框选择
    table.on('checkbox(currentTableFilter)', function (obj) {
        console.log(obj)
    });

    table.on('tool(currentTableFilter)', function (obj) {
        var data = obj.data;
        if (obj.event === 'delete') {
            b

            layer.confirm('确定要下架商品嘛', function (index) {
                obj.del();

                //待写下架商品

                layer.close(index);
            });

        }
        if (obj.event === 'edit') {
            form.render();
            // layer.alert('编辑行：<br>' + JSON.stringify(data))
            layer.open({
                type: 2
                , skin: "demo-class"
                , id: 'layerDemo'//防止重复弹出
                , content: 'poductEdit.html'
                , area: ['30%', '70%']
                , btn: '修改'
                , btnAlign: 'c' //按钮居中
                , shade: [0.3, '#2F4056']
                , resize: false
                , title: "修改商品"
                // , anim: 4
                , success: function (layero, index) {
                    var body = layer.getChildFrame('body', index);
                    body.contents().find('#pName').val(data.pname);
                    body.contents().find('#pArea').val(data.parea);
                    body.contents().find('#pMl').val(data.pml);
                    body.contents().find('#pId').val(data.pid);
                    form.render();

                }
                , yes: function (index) {
                    var dt = window['layui-layer-iframe' + index].getValues();
                    var dtppName = dt.ppName;
                    var dtppArea = dt.ppArea;
                    var dtpMl = dt.ppMl;
                    var dtppId = dt.ppId;
                    if (dt.ppName == "") {
                        layer.msg("请输入商品名称");
                        return -1;
                    }
                    if (dt.ppArea == "") {
                        layer.msg("请输入产地");
                        return -1;
                    }
                    axios.get('/api/product/updateProductByPId',
                        //{"pName":dtSpName, "pRemark": dtSpRemark, "pIs": 1}
                        {
                            params: {"pName": dtppName, "pArea": dtppArea, "pMl": dtpMl, "pId": dtppId}
                        })
                        .then(function (response) {
                            layer.msg("修改成功！");
                        })
                        .catch(function (error) {
                        })
                        .then(function (index) {
                            layer.closeAll();
                            table.reload('currentTableId', {
                                    page: {curr: 1}
                                }
                            );
                        });
                }
            })

            //修改商品信息

            layer.close(index);


        } else if (obj.event === 'uppshang') {
            layer.confirm('确定要恢复商品嘛', function (index) {
                obj.del();

                //待写恢复商品

                layer.close(index);
            });
        }
    });
});

